package top.xxyu;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import top.xxyu.utils.ZipUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SSHFile {

    public static final String zipFileTail = ".zip";
    public static final String serverSeparator = "\\";
    public  static void uploadFileDirByZip(ConfigBean config) throws FileNotFoundException {

//		ConfigBean config = ReadConfigInfo.getConfigInfo();
        //上传一个文件
        if(null != config) {
            String localZipFilePath = "";
            String localFileName = "";
            if(StringUtils.isNotEmpty(config.getLocalFilePath())) {
                localZipFilePath = config.getLocalFilePath()  + zipFileTail;
                int index = localZipFilePath.lastIndexOf("\\");
                localFileName = localZipFilePath.substring(index, localZipFilePath.length());
                //1.先压缩指定文件夹为zip
                FileOutputStream fileOutputStream = new FileOutputStream(new File(localZipFilePath));
                ZipUtils.toZip(config.getLocalFilePath(), fileOutputStream,true);
                //2.上传zip文件到服务器上
                try{
//		        	SSHWindows.scpPut("192.168.0.65", "test", "test", "E:/wangzgCode/西北旅游问答.png", "E:/wangzgCode/aa/bb");
                    SSHWindows.scpPut(config.getAddress(), config.getServerUserName(),
                            config.getServerPassword(), localZipFilePath,
                            config.getServerSavePath());
                }  catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    //删除临时文件zip
                    File removeFile = new File(localZipFilePath);
                    try{
                        removeFile.delete();
                    }catch(Exception e){
                        System.out.println("删除本地压缩文件异常！");
                    }
                }
                //判断远程文件夹是否存在，不存在需要级联创建远程文件夹
                String serverSaveDir = config.getServerSavePath() +serverSeparator +config.getServerSaveFileName();
                SSHWindows sshWindows = new SSHWindows();
                //删除已存在的文件夹  rmdir /s/q E:\wangzgCode\bb
                int lastIndex = config.getLocalFilePath().lastIndexOf("\\");
                String lastLocalDir = config.getLocalFilePath().substring(lastIndex + 1);
                if(lastLocalDir.equals(config.getServerSaveFileName())) {
                    String deleteSourceDirCommand = "rmdir /s/q "+ config.getServerSavePath()+"\\" + config.getServerSaveFileName();
                    sshWindows.execConmand(config, deleteSourceDirCommand);
                }
                //3.在服务器上解压zip到指定路径下,通过需要区分linux、windows服务器 ，脚本解析
                String serverZipTempFilePath = config.getServerSavePath()  + localFileName;
                String unzipCommand = "winrar x " + serverZipTempFilePath +
                        " -r  "+ config.getServerSavePath();
                System.out.println("unzipCommand:" + unzipCommand);
//				serverZipTempFilePath = serverZipTempFilePath.replace("/", "\\");
                String deleteServerCommand = "del /f/s/q "+ serverZipTempFilePath;
//				System.out.println("deleteServerCommand:" + deleteServerCommand);
                //执行命令，解压完文件
                sshWindows.execConmand(config, unzipCommand);

                try {
                    //延迟5秒再删除,可能解压没有结束
                    Thread.sleep(5000);
                    sshWindows.execConmand(config, deleteServerCommand);
                    //"ren E:\\wangzgCode\\sshLocal\\测试中文.log 新文件名11.txt"
//                    String renameCommand = "ren "+ config.getServerSavePath()+"\\"+ getServerPath(localZipFilePath).getSrcFileName() + " "+config.getServerSaveFileName() ;
                    String renameCommand = "ren "+ config.getServerSavePath()+"\\"+ localZipFilePath+ " "+config.getServerSaveFileName() ;
//					renameCommand = StringEncode.GBK2Unicode(renameCommand);
                    System.out.println("renameCommand:"+renameCommand);
                    sshWindows.execConmand(config, renameCommand);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //删除本地配置文件
//                ReadConfigInfo.deleteConfigFile();
            }

        }
    }

    public  static void downloadFileDirByZip(ConfigBean config) throws IOException, InterruptedException {
        String tempfileName = CustomFileUtils.generateRandomFilename() + zipFileTail;
        //下载一个文件
        if(null != config) {
            if(StringUtils.isNotEmpty(config.getServerFilePath())){
                //1.压缩要下载的文件夹  通过远程命令将对应的文件夹压缩为zip
                //压缩命令格式：winrar a d:/ftpServer/test2.zip  D:/ftpServer/test2/*.*  -r包含子文件夹
                String command = "winrar a -r -ep1 "+ config.getServerFilePath() + tempfileName +" " +config.getServerFilePath();
                System.out.println("command:" + command);
                SSHWindows sshWindows = new SSHWindows();
                //执行命令
                sshWindows.execConmand(config, command);
            }
            //2.下载压缩包zip
            try {
                SSHWindows.scpGet(config.getAddress(), config.getServerUserName(),
                        config.getServerPassword(), config.getServerFilePath() + tempfileName,
                        config.getLocalSavePath(),tempfileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.解压到本地指定文件夹下
            String zipFilePath = config.getLocalSavePath() + tempfileName;
            String desRenamePath = zipFilePath.substring(0, zipFilePath.length() - zipFileTail.length());


            int index = desRenamePath.lastIndexOf("\\");
            String newfolder = desRenamePath.substring(0, index + 1) + config.getLocalSaveFileName();
            //删除文件下所有文件
            FileUtils.deleteDirectory(new File(newfolder));

            ZipUtils.unZipFiles(new File(zipFilePath), config.getLocalSavePath());
            //5.删除服务器临时文件zip
            String serverFilePath = config.getServerFilePath() + tempfileName;
            String command = "del/f/s/q " + serverFilePath;
            System.out.println("downloadFileDirByZip:" + command);
            //解压完文件，直接删除压缩包
            SSHWindows sshWindows = new SSHWindows();
            sshWindows.execConmand(config, command);
            //延迟3秒，等待解压完毕
            Thread.currentThread().sleep(3000);
            System.out.println("delay 3s");
            File file = new File(desRenamePath);
            //删除文件下所有文件
            FileUtils.deleteDirectory(new File(newfolder));
            File srcFile = new File(desRenamePath);
            File renamedFile = new File(config.getLocalSavePath() + config.getLocalSaveFileName());
            srcFile.renameTo(renamedFile);



            //删除本地配置文件
//            ReadConfigInfo.deleteConfigFile();
        }
    }
}
